﻿using System;
using System.IO;

using ICSharpCode.SharpZipLib.Zip;

namespace NxStoreManage
{
    /// <summary>
    /// 文件压缩、解压
    /// </summary>
    public class ZipHelp
    {
        private static FastZip fz = new FastZip();

        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件的路径与名称</param>
        /// <param name="FilePath">   被压缩的文件路径</param>
        /// <param name="ZipPWD">     解压密码（null代表无密码）</param>
        /// <returns></returns>
        public static (bool Flag, string Msg) FileToZip(string zipFilePath, string FilePath, string ZipPWD)
        {
            string state = "Fail...";
            bool flag = false;
            try
            {
                FileInfo fi = new FileInfo(FilePath);
                string filename = fi.Name;
                string dirname = fi.DirectoryName;
                fz.Password = ZipPWD;
                fz.CreateZip(zipFilePath, dirname, false, filename);

                state = "Success !";
                flag = true;
            }
            catch (Exception ex)
            {
                state += "," + ex.Message;
            }
            return (flag, state);
        }

        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="DirPath">被压缩的文件夹路径</param>
        /// <param name="ZipPath">压缩文件夹的路径与名称</param>
        /// <param name="ZipPWD"> 解压密码（null代表无密码）</param>
        /// <returns></returns>
        public static (bool Flag, string Msg) DirToZip(string DirPath, string ZipPath, string ZipPWD)
        {
            string state = "Fail...";
            bool flag = false;
            try
            {
                fz.Password = ZipPWD;
                fz.CreateZip(ZipPath, DirPath, false, null);

                state = "Success !";
                flag = true;
            }
            catch (Exception ex)
            {
                state += "," + ex.Message;
            }
            return (flag, state);
        }

        /// <summary>
        /// 解压Zip
        /// </summary>
        /// <param name="DirPath">解压后存放路径</param>
        /// <param name="ZipPath">Zip的存放路径</param>
        /// <param name="ZipPWD"> 解压密码（null代表无密码）</param>
        /// <returns></returns>
        public static (bool Flag, string Msg) Compress(string DirPath, string ZipPath, string ZipPWD)
        {
            string state = "Fail...";
            bool flag = false;
            try
            {
                fz.Password = ZipPWD;
                fz.ExtractZip(ZipPath, DirPath, null);

                state = "Success !";
                flag = true;
            }
            catch (Exception ex)
            {
                state += "," + ex.Message;
            }
            return (flag, state);
        }
    }
}